import { useMutation } from "@tanstack/react-query";
import { oauthAPI } from "@/api";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import { useErrorHandler } from "@/lib/error-handler";
import type { ErrorResponse, Response } from "@/types/response";
import type { AxiosError } from "axios";
import type { Provider } from "@/types/oauth";

export interface OAuthLoginResponseData {
  auth_url: string;
}

type OAuthLoginResponse = Response & { data: OAuthLoginResponseData };

/**
 * OAuth 登录 hooks
 */
export const useOAuthLogin = () => {
  const { t } = useTranslation();
  const errorHandler = useErrorHandler();

  // OAuth 登录 mutation
  const oauthLoginMutation = useMutation({
    mutationFn: oauthAPI.login,
    onSuccess: (response: OAuthLoginResponse) => {
      if (response.code === 200) {
        // OAuth 登录成功，重定向到 OAuth 提供商
        window.location.href = response.data.auth_url;
      } else {
        // OAuth 登录失败
        toast.error(t("OAuth login failed"), {
          description:
            response.message ||
            t("An error occurred during OAuth login. Please try again."),
          duration: 5000,
        });
      }
    },
    onError: (error: AxiosError<ErrorResponse, unknown>) => {
      // 使用错误处理器获取错误信息
      const errorResult = errorHandler.handleApiError(error);

      // 根据错误类型显示不同颜色的弹窗
      if (errorResult.type === "warning") {
        toast.warning(t("OAuth login failed"), {
          description: errorResult.message,
          duration: 5000,
        });
      } else {
        toast.error(t("OAuth login failed"), {
          description: errorResult.message,
          duration: 5000,
        });
      }
      console.error("OAuth login error:", error);
    },
  });

  const login = (provider: Provider) => {
    oauthLoginMutation.mutate(provider);
  };

  const loginAsync = (provider: Provider) => {
    return oauthLoginMutation.mutateAsync(provider);
  };

  return {
    login,
    loginAsync,
    isLogging: oauthLoginMutation.isPending,
    loginError: oauthLoginMutation.error,
  };
};
